# 模拟登陆
import datetime
import random
import time
from apscheduler.schedulers.background import BackgroundScheduler
from pyquery import PyQuery as pq
import requests

url = 'http://172.45.1.9/cas/login'
UN_ZHAOBO = 'F081F4E4E27C4402993130F964AAFA5A'
# 杨丹成
UN_YDC = 'A79D6839434647979697B83C424C59C4'
UN_YJJ = 'B13E928889B64D619EC392E047969868'
# 刘蔚然
UN_LWR = 'liuweiran'
# 龚永征
UN_GYZ = 'gongyongzheng'
# 何彦
UN_HEYAN = '88A8D633A3CD4FD09FFF79B15DDE447D'

class Login(object):
    def __init__(self):
        self.headers = {
            # http://172.45.1.9/cas/login?se…ice=http%3A%2F%2F172.45.1.2%2F
            'Referer': 'http://172.45.1.9',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
            'Host': '172.45.1.9'
        }

        self.signin_headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
        }

        self.login_url = 'http://172.45.1.9/cas/login'
        self.post_url = 'http://172.45.1.9/cas/login?service=http://172.45.1.2/'
        self.logined_url = 'http://172.45.1.2/risen/home/index.action'
        self.kaoqing_url = 'http://172.45.1.55/risen/home/index.action?item-box-title_04000t$kaoqing'
        # 网络日志界面
        self.doc_url = 'http://172.45.1.55/risen/oa/dailydynamic/doDocumentNew.action?strMap.daildata='
        # 写日志
        self.write_doc_url = 'http://172.45.1.55/risen/oa/dailydynamic/doDocumentExecuteAjax.action'
        self.signin_url = 'http://172.45.1.55/risen/oa/mag/OaSignin/signin.action'
        self.session = requests.Session()

    def gen_param(self, name, password, username):
        response = self.session.get(self.login_url, headers = self.headers)
        doc = pq(response.text)
        lt = doc('input[name="lt"]').attr('value')
        execution = doc('input[name="execution"]').attr('value')
        eventId = doc('input[name="_eventId"]').attr('value')
        print(lt, execution, eventId)
        return {
            '_eventId': eventId,
            'execution': execution,
            'lt': lt,
            'name': name,
            'password': password,
            'username': username
        }

    def gen_doc_param(self, response):
        # response = self.session.get(self.doc_url, headers = self.signin_headers)
        doc = pq(response.text)

        return {
            'oaddCdate': doc('#oaddCdate').attr('value'),
            'oaddContent': ' ',
            'oaddCreatorname': doc('#oaddCreatorname').attr('value'),
            'oaddCreatoruuid': doc('#oaddCreatoruuid').attr('value'),
            'oaddCusr': doc('#oaddCusr').attr('value'),
            'oaddDate': doc('#oaddDate').attr('value'),
            'oaddItemuuid': doc('#oaddItemuuid').attr('value'),
            'oaddOrgname': doc('#oaddOrgname').attr('value'),
            'oaddOrguuid': doc('#oaddOrguuid').attr('value'),
            'oaddRemark': '',
            'oaddUnid': doc('#oaddUnid').attr('value'),
            'oaddUuid': doc('#oaddUuid').attr('value'),
            'strMap.currentActionOS': 'actionSave'
        }

    def login(self, name, password, username, signin_value = 1):
        '''
        登陆方法
        :return:
        '''
        post_data = self.gen_param(name, password, username)
        response = self.session.post(self.post_url, data = post_data, headers = self.headers)
        if response.status_code == 200:
            print(name, "登陆成功!", end = "    ")

        # 进主页面
        # response = self.session.get(self.logined_url, headers = self.headers)
        # if response.status_code == 200:
        #     print(name, "打开主页成功!")
        #     print(response.cookies)
            # print(response.text)

        print("休眠 5 秒...", end = "    ")
        time.sleep(5)

        # 去考勤页面
        response = self.session.get(self.kaoqing_url, headers = self.signin_headers)
        if response.status_code == 200:
            # print(response.text)
            print("获取考勤界面", end = "    ")

        print("休眠 5 秒...")
        time.sleep(5)

        # 去网络日志页面, 获取参数
        today = datetime.datetime.utcnow().strftime("%Y-%m-%d")
        self.doc_url += today
        response = self.session.get(self.doc_url, headers = self.signin_headers)
        if response.status_code == 200:
            dict_param = self.gen_doc_param(response)
            print('获取网络日志参数:', dict_param)

        # 写日志
        response = self.session.post(self.write_doc_url, data = dict_param, headers = self.signin_headers)
        if response.status_code == 200:
            print('写入日志...', '服务器返回结果:', response.text)

        # 签到签出
        post_data = {'strMap.signin': str(signin_value)}
        response = self.session.post(self.signin_url, data=post_data, headers=self.signin_headers)
        if response.status_code == 200:
            if signin_value == 1:
                print('发送签到请求...', '服务器返回结果:', response.text)
                print(name, "签到成功! 签到时间为", datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
            if signin_value == 2:
                print('发送签出请求...', '服务器返回结果:', response.text)
                print(name, "签出成功! 签出时间为", datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))

def time_task_singin_zhaobo():
    sleeptime = random.randint(10, 20)
    time.sleep(sleeptime)
    login = Login()
    login.login('赵波', '880322', UN_ZHAOBO, 1)

def time_task_singin_out_zhaobo():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('赵波', '880322', UN_ZHAOBO, 2)

def time_task_singin_ydc():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('杨丹成', '123456', UN_YDC, 1)

def time_task_singin_out_ydc():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('杨丹成', '123456', UN_YDC, 2)

def time_task_singin_yjj():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('余菁菁', '123456', UN_YJJ, 1)

def time_task_singin_out_yjj():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('余菁菁', '123456', UN_YJJ, 2)

def time_task_singin_gyz():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('龚永征', 'money874100', UN_GYZ, 1)

def time_task_singin_out_gyz():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('龚永征', 'money874100', UN_GYZ, 2)

def time_task_singin_lwr():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('刘蔚然', '2', UN_LWR, 1)

def time_task_singin_out_lwr():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('刘蔚然', '2', UN_LWR, 2)

def time_task_singin_heyan():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('何彦', '811115', UN_HEYAN, 1)

def time_task_singin_out_heyan():
    sleeptime = random.randint(10, 50)
    time.sleep(sleeptime)
    login = Login()
    login.login('何彦', '811115', UN_HEYAN, 2)

if __name__ == '__main__':
    # 创建后台执行的 schedulers
    scheduler = BackgroundScheduler()
    # 添加调度任务
    # 触发器选择 cron， 周一到周五
    # scheduler.add_job(time_task_singin_zhaobo, 'cron', day_of_week='mon-fri', hour='7', minute='35')
    scheduler.add_job(time_task_singin_zhaobo, 'cron', day_of_week='mon-fri', hour='7', minute='52')
    scheduler.add_job(time_task_singin_out_zhaobo, 'cron', day_of_week='mon-fri', hour='18', minute='03')

    # scheduler.add_job(time_task_singin_ydc, 'cron', day_of_week='mon-fri', hour='7', minute='37')
    scheduler.add_job(time_task_singin_ydc, 'cron', day_of_week='mon-fri', hour='7', minute='54')
    scheduler.add_job(time_task_singin_out_ydc, 'cron', day_of_week='mon-fri', hour='17', minute='58')

    # scheduler.add_job(time_task_singin_yjj, 'cron', day_of_week='mon-fri', hour='7', minute='39')
    scheduler.add_job(time_task_singin_yjj, 'cron', day_of_week='mon-fri', hour='7', minute='56')
    scheduler.add_job(time_task_singin_out_yjj, 'cron', day_of_week='mon-fri', hour='17', minute='40')

    # scheduler.add_job(time_task_singin_gyz, 'cron', day_of_week='mon-fri', hour='7', minute='41')
    scheduler.add_job(time_task_singin_gyz, 'cron', day_of_week='mon-fri', hour='7', minute='57')
    scheduler.add_job(time_task_singin_out_gyz, 'cron', day_of_week='mon-fri', hour='17', minute='45')

    # scheduler.add_job(time_task_singin_lwr, 'cron', day_of_week='mon-fri', hour='7', minute='43')
    scheduler.add_job(time_task_singin_lwr, 'cron', day_of_week='mon-fri', hour='7', minute='48')
    scheduler.add_job(time_task_singin_out_lwr, 'cron', day_of_week='mon-fri', hour='17', minute='50')

    # scheduler.add_job(time_task_singin_heyan, 'cron', day_of_week='mon-fri', hour='7', minute='45')
    scheduler.add_job(time_task_singin_heyan, 'cron', day_of_week='mon-fri', hour='7', minute='50')
    scheduler.add_job(time_task_singin_out_heyan, 'cron', day_of_week='mon-fri', hour='17', minute='30')
    # 启动调度任务
    scheduler.start()

    while True:
        time.sleep(5)
    # login = Login()
    # 签出
    # login.login('赵波', '880322', UN_ZHAOBO, 2)
    # login.login('杨丹成', '123456', UN_YDC, 1)

